package abq2.jic.jic.plugin.operate.jianli;

import com.alibaba.fastjson.JSONObject;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.ext.form.control.Markdown;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.DispatchServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;

import java.text.SimpleDateFormat;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Map;

public class GetAnswerEvaluate extends AbstractBillPlugIn {
    @Override
    public void registerListener(EventObject e) {
        //注册点击事件
        super.registerListener(e);
        this.addItemClickListeners("abq2_toolbarap");
    }

    public void itemClick(ItemClickEvent e) {
        super.itemClick(e);
        if (e.getItemKey().equalsIgnoreCase("abq2_analysis_button")) {
            JSONObject jsonResultObject = new JSONObject();
            jsonResultObject.put("question",this.getModel().getValue("abq2_question"));
            jsonResultObject.put("answer",this.getModel().getValue("abq2_answer"));



            //调用GPT开发平台微服务
            Map<String , String> variableMap = new HashMap<>();
            variableMap.put("taskResult", jsonResultObject.toJSONString());

            Object[] params = new Object[] {
                    //GPT提示编码
                    getPromptFid("prompt-240529903078AB"),
                    "",
                    variableMap
            };
            Map<String, Object> result = DispatchServiceHelper.invokeBizService("ai", "gai", "GaiPromptService", "syncCall", params);
            JSONObject jsonObjectResult = new JSONObject(result);
            JSONObject jsonObjectData = jsonObjectResult.getJSONObject("data");
            //设置值
            this.getModel().setValue("abq2_analysis", jsonObjectData.getString("llmValue"));
            Markdown mk = this.getView().getControl("abq2_markdownap");
            mk.setText(jsonObjectData.getString("llmValue"));
        }

    }

    //获取GPT提示的Fid
    public long getPromptFid(String billNo) {
        DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle("gai_prompt",
                "number," +
                        "id",
                (new QFilter("number", QCP.equals, billNo)).toArray());
        return dynamicObject.getLong("id");
    }

    @Override
    public void afterBindData(EventObject eventObject) {
        Markdown mk = this.getView().getControl("abq2_markdownap");
        mk.setText(this.getModel().getValue("abq2_analysis").toString());
    }
}
